package es.javamyadmin.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.javamyadmin.dao.TriggersDAO;
import es.javamyadmin.pojo.Error;

/**
 * Servlet que crea un trigger
 * @author Emilio Javier Castillo Gonzalez
 * @author Hector Delgado Duran
 */
public class CreateTrigger extends HttpServlet {

	
	/**
	 * 
	 */
	private static final long serialVersionUID = 6704771499940254308L;

	/**
	 * Metodo que crea un trigger
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String nombre = request.getParameter("nombre");
		String tabla = request.getParameter("tabla");
		String tiempo = request.getParameter("tiempo");
		String evento = request.getParameter("evento");
		String definicion = request.getParameter("definicion");
		String user =  request.getParameter("user");
		String pass =  request.getParameter("pass");
		String port =  request.getParameter("port");
		String host =  request.getParameter("host");
		String database =  request.getParameter("database");
		
		Error error = null;
		
		if((nombre != null && !nombre.trim().equals("")) && (tabla != null && !tabla.trim().equals("")) && (tiempo != null && !tiempo.trim().equals(""))
				&& (evento != null && !evento.trim().equals("")) && (definicion != null && !definicion.trim().equals(""))){
			TriggersDAO tri = new TriggersDAO();
			tri.setPath(getServletContext().getResourceAsStream("/WEB-INF/properties/mensajes.properties"));
			String query = "CREATE TRIGGER " + nombre + " " + tiempo + " " + evento + " ON " + tabla + " FOR EACH ROW BEGIN " + definicion + " END";
			System.out.println(query);
			error = tri.createTrigger(database, user, pass, host, port, query);
			if(error == null){
				request.setAttribute("ok", "Se ha creado el trigger satisfactoriamente.");
				request.getRequestDispatcher("/jsp/triggers-bd.jsp").forward(request,response);
			}else{
				if(error.getError() != null){
					request.setAttribute("error", error.getError());
					if(error.getDescripcion() != null){
						request.setAttribute("descripcion", error.getDescripcion());
					}
				}
				request.getRequestDispatcher("/jsp/nuevo-triggers.jsp").forward(request,response);
			}
		}else{
			request.setAttribute("error", "Algun campo del formulario no ha sido rellenado");
			request.getRequestDispatcher("/jsp/nuevo-triggers.jsp").forward(request,response);
		}
		
	}

}
